package com.anji.sp.service.impl;

import com.anji.sp.service.SpDownloadService;
import com.anji.sp.util.file.FileProfileConfig;
import com.anji.sp.util.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;

/**
 * Created by raodeming on 2021/8/20.
 */
@Service
@Slf4j
public class SpDownloadServiceImpl implements SpDownloadService {

    @Override
    public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response, String filename) {
        try {
            String userAgent = request.getHeader("User-Agent");
            boolean isIeBrowser = userAgent.indexOf("MSIE") > 0;


            String fileSuffix = filename.substring(filename.lastIndexOf("."));

            // /app/file-sp
            String profile = FileProfileConfig.getProfile();
            profile = profile + "/apk/" + filename;

            //根据文件后缀来判断，是显示图片\视频\音频，还是下载文件
            File file = new File(profile);
            ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
            builder.contentLength(file.length());
            //application/octet-stream 二进制数据流（最常见的文件下载）
            builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
            filename = URLEncoder.encode(filename, "UTF-8");
            if (isIeBrowser) {
                builder.header("Content-Disposition", "attachment; filename=" + filename);
            } else {
                builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + filename);
            }

            return builder.body(FileUtils.readFileToByteArray(file));
        } catch (Exception e) {
            log.error("file download error: {}", e);
            return null;
        }
    }
}
